#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：zhcx-service-test 
@File    ：strategy.py
@Author  ：关依林
@Date    ：2023/12/5 16:03 
'''
import datetime

from common.setting import ensure_path_sep
from testcases.ProductGrading_Strategy.AmazonListing.dao.query_sql_method import getStrategyData
from utils.mysqlUtils.db_utils import DB
import requests
import json

filePath = ensure_path_sep("\\config\\config.yaml")

def couponAPI(matchingResult):

    url = "http://amazonapi.zhcxkj.com/Coupon/Search"
    res = []
    nowTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for id in range(0, len(matchingResult), 1000) :
        data = []
        asinSet = matchingResult[id: id+1000]
        for asin in asinSet:
            str = {"orderSourceId": 5005,"asin": asin}
            data.append(str)
        payload = json.dumps({
            "input": data
        })
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic YXBpdXNlcjpBNCNDMjcyRjQ3Ql9CMTJDRC01OA=='
        }
        response = requests.request("POST", url, headers=headers, data=payload).json()["data"]
        tempSet = list(filter(lambda x: nowTime > x["EndTime"], response))
        res += tempSet
    return res

def connectMysql(dbName):

    cursor = DB(filePath, dbName)
    return cursor

cursorListing = connectMysql("Java_Coupon_Test")
cursorStrategy = connectMysql("Java_centerStrategy_Test")

# 获取Listing分级策略ASIN明细
def getStrategyIntersection(strategyIdSet, orderSourceId):

    res = []
    for strategyId in strategyIdSet:
        result = getStrategyData(
            cursorStrategy, strategyId, orderSourceId
        )
        res += result
    return list(set(res))

# ASIN明细校验
def getCouponIntersection(couponIdSet , StrategyIdSet, orderSourceId):

    asinSet = []
    # 获取优惠券ID下的Asin明细
    for id in couponIdSet:
        couponSql = f"SELECT asin FROM coupon_asin_0 WHERE coupon_id = {id}"
        tempSet = cursorListing.execute_sql_many(couponSql)
        asinSet += [i["asin"] for i in tempSet]
    # 获取策略下的Asin明细
    strategyResult = getStrategyIntersection(StrategyIdSet, orderSourceId)
    # matchingResult = set(asinSet) - set(strategyResult)
    matchingResult = set(strategyResult) - set(asinSet)
    res = couponAPI(list(matchingResult))
    return res

def getCouponAsin(couponId):

    tempList = []
    couponSql = f"SELECT asins FROM coupon_0 WHERE strategy_id = {couponId}"
    asinSet = cursorListing.execute_sql_many(couponSql)
    for i in asinSet:
        tempSet = i["asins"].split(";")
        tempList += tempSet
    matchingResult = list(filter(lambda x: x != "", tempList))

    return matchingResult



def getAsinErr(couponIdSet , couponStrategyIdSet, strategyIdSet, orderSourceId):

    StrategyAsinSet = getStrategyIntersection(strategyIdSet, orderSourceId)
    GenerateAsinSet = getCouponIntersection(couponIdSet ,couponStrategyIdSet, orderSourceId)
    differentResult = list(set(StrategyAsinSet) - set(GenerateAsinSet))
    return differentResult




if __name__ == '__main__':

    # getAsinErr(
    #     couponIdSet=[59317, 59316, 59315],
    #     StrategyIdSet=[], strategyIdSet, orderSourceId
    # )
    getCouponIntersection(
        couponIdSet = [59317, 59316, 59315],
        StrategyIdSet = [262,261],
        orderSourceId = 5005
    )
    # print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # print(getCouponAsin())
    # print(filePath)
    # orderSourceId = 5005
    # strategyIdSet = [261, 262]
    # res = getStrategyIntersection(strategyIdSet, orderSourceId)